<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">巴克什找房后台管理系统</h3>

      <!-- 登录方式切换 -->
      <div class="login-tabs">
        <div
          :class="['tab-item', loginType === 'account' ? 'active' : '']"
          @click="switchLoginType('account')"
        >
          账号密码登录
        </div>
        <div
          :class="['tab-item', loginType === 'phone' ? 'active' : '']"
          @click="switchLoginType('phone')"
        >
          手机验证码登录
        </div>
      </div>

      <!-- 账号密码登录表单 -->
      <div v-if="loginType === 'account'">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="账号"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
      </div>

      <!-- 手机验证码登录表单 -->
      <div v-if="loginType === 'phone'">
        <el-form-item prop="phoneNumber">
          <el-input
            v-model="loginForm.phoneNumber"
            type="text"
            auto-complete="off"
            placeholder="手机号码"
          >
            <svg-icon
              slot="prefix"
              icon-class="phone"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="phoneCode">
          <el-input
            v-model="loginForm.phoneCode"
            type="text"
            auto-complete="off"
            placeholder="验证码"
            @keyup.enter.native="handleLogin"
            style="width: 63%"
          >
            <svg-icon
              slot="prefix"
              icon-class="validCode"
              class="el-input__icon input-icon"
            />
          </el-input>
          <el-button
            :disabled="sendingCode || !loginForm.phoneNumber"
            @click="sendPhoneCode"
            class="get-code-btn"
            size="small"
          >
            {{ sendingCode ? `${countDown}s后重新发送` : "获取验证码" }}
          </el-button>
        </el-form-item>
      </div>

      <!-- 公共部分：验证码和登录按钮 -->
      <el-form-item
        prop="code"
        v-if="captchaEnabled && loginType === 'account'"
      >
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon
            slot="prefix"
            icon-class="validCode"
            class="el-input__icon input-icon"
          />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>

      <el-checkbox
        v-model="loginForm.rememberMe"
        style="margin: 0px 0px 25px 0px"
        v-if="loginType === 'account'"
        >记住密码</el-checkbox
      >

      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width: 100%"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right" v-if="register && loginType === 'account'">
          <router-link class="link-type" :to="'/register'"
            >立即注册</router-link
          >
        </div>
      </el-form-item>
    </el-form>
    <!-- 底部 -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import { getPhoneCode, phoneLogin } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";

export default {
  name: "Login",
  data() {
    return {
      title: process.env.VUE_APP_TITLE,
      codeUrl: "",
      loginType: "account", // account: 账号密码登录, phone: 手机验证码登录
      sendingCode: false, // 是否正在发送验证码
      countDown: 60, // 倒计时秒数
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: "",
        phoneNumber: "",
        phoneCode: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
        phoneNumber: [
          { required: true, trigger: "blur", message: "请输入手机号码" },
          {
            pattern: /^1[3-9]\d{9}$/,
            trigger: "blur",
            message: "请输入正确的手机号码",
          },
        ],
        phoneCode: [
          { required: true, trigger: "blur", message: "请输入验证码" },
          { min: 4, max: 6, trigger: "blur", message: "验证码长度不正确" },
        ],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: true,
      redirect: undefined,
      countDownTimer: null, // 倒计时计时器
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  beforeDestroy() {
    // 清除倒计时计时器
    if (this.countDownTimer) {
      clearInterval(this.countDownTimer);
    }
  },
  methods: {
    // 切换登录方式
    switchLoginType(type) {
      this.loginType = type;
      // 切换时重置表单验证
      this.$refs.loginForm.clearValidate();
    },

    // 获取图形验证码
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },

    // 获取手机验证码
    sendPhoneCode() {
      // 验证手机号
      this.$refs.loginForm.validateField("phoneNumber", (error) => {
        if (!error) {
          this.sendingCode = true;

          // 调用获取验证码接口
          getPhoneCode(this.loginForm)
            .then((response) => {
              this.$message.success("验证码发送成功，请查收");

              // 开始倒计时
              this.countDownTimer = setInterval(() => {
                this.countDown--;
                if (this.countDown <= 0) {
                  clearInterval(this.countDownTimer);
                  this.sendingCode = false;
                  this.countDown = 60;
                }
              }, 1000);
            })
            .catch((error) => {
              this.sendingCode = false;
              this.$message.error(error.message || "验证码发送失败");
            });
        }
      });
    },

    // 从cookie获取记住的账号密码
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        ...this.loginForm,
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },

    // 处理登录
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;

          // 账号密码登录
          if (this.loginType === "account") {
            // 处理记住密码
            if (this.loginForm.rememberMe) {
              Cookies.set("username", this.loginForm.username, { expires: 30 });
              Cookies.set("password", encrypt(this.loginForm.password), {
                expires: 30,
              });
              Cookies.set("rememberMe", this.loginForm.rememberMe, {
                expires: 30,
              });
            } else {
              Cookies.remove("username");
              Cookies.remove("password");
              Cookies.remove("rememberMe");
            }

            // 调用原有登录逻辑
            this.$store
              .dispatch("Login", this.loginForm)
              .then(() => {
                this.$router
                  .push({ path: this.redirect || "/" })
                  .catch(() => {});
              })
              .catch(() => {
                this.loading = false;
                if (this.captchaEnabled) {
                  this.getCode();
                }
              });
          }
          // 手机验证码登录
          else {
            phoneLogin(this.loginForm)
              .then((res) => {
                if (res.code === 200) {
                  this.$message.success("登录成功");

                  const token = res.data.token;
                  const userInfo = res.data;

                  if (token && userInfo) {
                    this.$store.commit('SET_TOKEN', token);
                    this.$store.commit('SET_USER_INFO', userInfo);
                    this.$router
                      .push({ path: this.redirect || "/" })
                      .catch(() => {});
                  } else {
                    this.$router.push({ path: this.redirect || "/" })
                      .catch(() => {});
                  }
                } else {
                  this.$router.push({ path: this.redirect || "/" })
                    .catch(() => {});
                }
              })
              .catch((error) => {
                this.$router.push({ path: this.redirect || "/" })
                  .catch(() => {});
              })
              .finally(() => {
                this.loading = false;
              });
          }
        }
      });
    }
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 25px auto;
  text-align: center;
  color: #333;
  font-weight: 600;
  font-size: 22px;
  letter-spacing: 1px;
}

.login-form {
  border-radius: 10px;
  background: #ffffff;
  width: 420px;
  padding: 30px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
  z-index: 1;
  
  .el-input {
    height: 42px;
    input {
      height: 42px;
      border-radius: 4px;
    }
  }
  
  .input-icon {
    height: 42px;
    width: 16px;
    margin-left: 5px;
  }
}

// 登录方式切换样式
.login-tabs {
  display: flex;
  margin-bottom: 25px;
  border-radius: 20px;
  background-color: #f5f7fa;
  padding: 4px;
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 10px 0;
    cursor: pointer;
    position: relative;
    color: #606266;
    transition: all 0.3s;
    border-radius: 20px;
    
    &:hover {
      color: #409eff;
    }
    
    &.active {
      color: #fff;
      background-color: #409eff;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
    }
  }
}

// 验证码按钮样式
.get-code-btn {
  width: 35%;
  float: right;
  height: 42px;
  line-height: 42px;
  padding: 0;
  border-radius: 4px;
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #606266;
  
  &:not(:disabled):hover {
    background-color: #ecf5ff;
    border-color: #b3d8ff;
    color: #409eff;
  }
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  height: 42px;
  border-radius: 4px;
  font-size: 16px;
  letter-spacing: 2px;
  
  &:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 42px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
    border-radius: 4px;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 42px;
}
</style>